package com.leyou.search.scheduler;

import com.leyou.auth.client.AuthClient;
import com.leyou.search.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @date: 2021/4/12 0012 15:19
 * @description: 向授权中心申请合法token定时任务
 */
@Component
@Slf4j
public class AppTokenScheduler {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProperties;
    //添加一个成员变量，存储申请到token
    private String appToken;


    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L; //24小时

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void appToken() {
        while (true) {
            try {
                String appToken = authClient.authorization(jwtProperties.getApp().getServiceName(), jwtProperties.getApp().getSecret());
                this.appToken = appToken;
                log.info("【申请token】申请token成功，服务名：" + jwtProperties.getApp().getServiceName());
                //System.out.println(appToken);
                //申请成功退出循环
                break;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【申请token】申请token失败，原因：" + e.getMessage());
                //申请token，则隔10秒后重试
                try {
                    Thread.sleep(TOKEN_RETRY_INTERVAL);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
        }
    }
    /**
     * 提供get方法供外部使用
     */
    public String getAppToken() {
        return appToken;
    }
}
